package time_task

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

// 使用者可能要在前面封装一层
func CreateTomorrowTable(dbName, oldTable, newTable string) func() error {
	return func() error {
		CreateTodayTable(dbName, oldTable, newTable)()
		t := time.Now().Add(24 * time.Hour).Format("20060102")
		sql := fmt.Sprintf(`
			CREATE TABLE IF NOT EXISTS %v LIKE %v
		`, newTable+t, oldTable)

		o := orm.NewOrm()
		err := o.Using(dbName)
		if err != nil {
			return err
		}
		_, err = o.Raw(sql).Exec()
		return err
	}
}

func CreateTodayTable(dbName, oldTable, newTable string) func() error {
	return func() error {
		t := time.Now().Format("20060102")
		sql := fmt.Sprintf(`
			CREATE TABLE IF NOT EXISTS %v LIKE %v
		`, newTable+t, oldTable)

		o := orm.NewOrm()
		err := o.Using(dbName)
		if err != nil {
			return err
		}
		_, err = o.Raw(sql).Exec()
		return err
	}
}

func CreateYesterdayTable(dbName, oldTable, newTable string) func() error {
	return func() error {
		CreateTwoDayBeforeTable(dbName, oldTable, newTable)()
		t := time.Now().Add(-24 * time.Hour).Format("20060102")
		sql := fmt.Sprintf(`
			CREATE TABLE IF NOT EXISTS %v LIKE %v
		`, newTable+t, oldTable)

		o := orm.NewOrm()
		err := o.Using(dbName)
		if err != nil {
			return err
		}
		_, err = o.Raw(sql).Exec()
		return err
	}
}

func CreateTwoDayBeforeTable(dbName, oldTable, newTable string) func() error {
	return func() error {
		t := time.Now().Add(-48 * time.Hour).Format("20060102")
		sql := fmt.Sprintf(`
			CREATE TABLE IF NOT EXISTS %v LIKE %v
		`, newTable+t, oldTable)

		o := orm.NewOrm()
		err := o.Using(dbName)
		if err != nil {
			return err
		}
		_, err = o.Raw(sql).Exec()
		return err
	}
}

// 使用者可能要在前面封装一层
func CreateNextMonthTable(dbName, oldTable, newTable string) func() error {
	return func() error {
		CreateThisMonthTable(dbName, oldTable, newTable)()
		thisMonth := time.Now()
		nextMonth := thisMonth.AddDate(0, 1, 0)
		t1 := nextMonth.Format("200601")
		sql := fmt.Sprintf(`
			CREATE TABLE IF NOT EXISTS %v LIKE %v
		`, newTable+t1, oldTable)

		o := orm.NewOrm()
		err := o.Using(dbName)
		if err != nil {
			return err
		}
		_, err = o.Raw(sql).Exec()
		return err
	}
}

func CreateThisMonthTable(dbName, oldTable, newTable string) func() error {
	return func() error {
		t := time.Now().Format("200601")
		sql := fmt.Sprintf(`
			CREATE TABLE IF NOT EXISTS %v LIKE %v
		`, newTable+t, oldTable)

		o := orm.NewOrm()
		err := o.Using(dbName)
		if err != nil {
			return err
		}
		_, err = o.Raw(sql).Exec()
		return err
	}
}

//获取最大自增id
func GetMaxAutoIncrementId(dbName, tableName string) (int64, error) {
	sql := fmt.Sprintf(`
		SELECT auto_increment FROM information_schema.TABLES
		WHERE TABLE_SCHEMA = "%v" AND TABLE_NAME = "%v"
	`, dbName, tableName)
	var MaxId int64
	o := orm.NewOrm()
	err := o.Raw(sql).QueryRow(&MaxId)
	if err != nil {
		return 0, err
	}
	return MaxId, nil
}

//获取最大主键id
func GetMaxPrimaryKey(dbName, tableName, primaryKey string) (int64, error) {
	sql := fmt.Sprintf(`
		SELECT MAX(%v) FROM %v
	`, primaryKey, tableName)
	var MaxId int64
	o := orm.NewOrm()
	err := o.Using(dbName)
	if err != nil {
		return 0, err
	}
	err = o.Raw(sql).QueryRow(&MaxId)
	if err != nil {
		return 0, err
	}
	return MaxId, nil
}

// 清理房间，邮件
func ClearDueRoom() error {
	sql := fmt.Sprintf("CALL p_clear_due_proom;")
	o := NewDBOrm(DBChess)
	_, err := o.Raw(sql).Exec()
	return err
}

// 清理网络延迟数据
func ClearNetDelay() error {
	sql := fmt.Sprintf("DELETE FROM %v WHERE 1", TableNetDelay)
	o := NewDBOrm(DBChess)
	_, err := o.Raw(sql).Exec()
	return err
}

// 每天清除半个月前的错误日志
func ClearClientError() error {
	now := time.Now().Unix()
	sql := fmt.Sprintf("DELETE FROM %v WHERE error_time <= %v", TableClientError, now-15*24*3600)
	o := NewDBOrm(DBChessLog)
	_, err := o.Raw(sql).Exec()
	return err
}

// 每天清除半个月前的打点日志
func ClearSubmitLog() error {
	now := time.Now().Unix()
	sql := fmt.Sprintf("DELETE FROM %v WHERE error_time <= %v", TableSubmitLog, now-15*24*3600)
	o := NewDBOrm(DBChessLog2)
	_, err := o.Raw(sql).Exec()
	return err
}

//新建或更新数据(agent,group)
func NewOrUpdateChessLog(data map[string]interface{}, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	values, sql := InsertOrUpdateSql(tableName, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//更新代理的数据
func UpdateDayAgent(data map[string]interface{}, id int64, createTime, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	condition := fmt.Sprintf(`agent_id = %v AND create_time = %v`, id, createTime)
	values, sql := UpdateSql(tableName, data, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//新建月报表(agent or group)
func NewMonth(data map[string]interface{}, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	values, sql := InsertSql(tableName, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//更新月报表(month_agent,month_agent_level1)
func UpdateMonthAgent(data map[string]interface{}, agentId int64, createTime, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	condition := fmt.Sprintf(`agent_id = %v AND create_time = %v`, agentId, createTime)
	values, sql := UpdateSql(tableName, data, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//增量地更新月报表(month_agent,month_agent_level1)
func UpdateAddMonthAgent(data map[string]interface{}, agentId int64, createTime, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	//fmt.Println("------------######增量地更新:", agentId, "时间:", createTime)
	//fmt.Printf("--------------data:%#v\n", data)
	o := NewOrm(multiOrm, DBChessLog)
	condition := fmt.Sprintf(`agent_id = %v AND create_time = %v`, agentId, createTime)
	values, sql := UpdateAndAddSql(tableName, data, condition)
	//fmt.Println("------------values:", values)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//更新月报表(month_group)
func UpdateMonthGroup(data map[string]interface{}, groupId int64, createTime, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	condition := fmt.Sprintf(`group_id = %v AND create_time = %v`, groupId, createTime)
	values, sql := UpdateSql(tableName, data, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//增量地更新月报表(month_group)
func UpdateAddMonthGroup(data map[string]interface{}, groupId int64, createTime, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	condition := fmt.Sprintf(`group_id = %v AND create_time = %v`, groupId, createTime)
	values, sql := UpdateAndAddSql(tableName, data, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//
func IsMonthAgentExist(agentId int64, tableName string, multiOrm ...orm.Ormer) bool {
	sql := fmt.Sprintf(`
		SELECT
			agent_id
		FROM
			%v
		WHERE
			agent_id = ?
		LIMIT 1
		`, tableName)
	o := NewOrm(multiOrm)
	var p int64
	err := o.Raw(sql, agentId).QueryRow(&p)
	if CheckNoExist(err) {
		return false
	}
	return true
}

func IsMonthGroupExist(groupId int64, tableName string, multiOrm ...orm.Ormer) bool {
	sql := fmt.Sprintf(`
		SELECT
			group_id
		FROM
			%v
		WHERE
			group_id = ?
		LIMIT 1
		`, tableName)
	o := NewOrm(multiOrm)
	var p int64
	err := o.Raw(sql, groupId).QueryRow(&p)
	if CheckNoExist(err) {
		return false
	}
	return true
}
